package cn.didi.feidi.androidorder.fragment;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewStub;
import android.widget.Toast;

import org.greenrobot.greendao.async.AsyncOperation;
import org.greenrobot.greendao.async.AsyncOperationListener;
import org.greenrobot.greendao.async.AsyncSession;
import org.greenrobot.greendao.query.QueryBuilder;

import java.util.ArrayList;
import java.util.List;

import cn.didi.feidi.androidorder.OrderApplication;
import cn.didi.feidi.androidorder.R;
import cn.didi.feidi.androidorder.activity.ConfirmOrderActivity;
import cn.didi.feidi.androidorder.adapter.MainShoppingCarRecyclerViewAdapter;
import cn.didi.feidi.androidorder.assembly.FeidiActionBar;
import cn.didi.feidi.androidorder.databinding.FragmentMainShoppingCarBinding;
import cn.didi.feidi.androidorder.databinding.FragmentMainShoppingCarViewStubBinding;
import cn.didi.feidi.androidorder.manager.UserManager;
import cn.didi.feidi.androidorder.model.ShoppingCar;


/**
 * Created by jinxiong on 2017/8/19.
 */

public class ShoppingCarFragment extends FeiDiMainBaseFragment {

    private static final String TAG = "ShoppingCarFragment";
    private static String ALL_SELECT = "全选";
    private final int REQUEST_CODE = 1;
    private final int CONFIRM_ORDER_RESULT = 2;

    FragmentMainShoppingCarBinding binding;
    FragmentMainShoppingCarViewStubBinding viewStubBinding;
    MainShoppingCarRecyclerViewAdapter adapter;
    AsyncSession asyncSession;

    private boolean isSelected;
    private boolean isLoading;
    private boolean isEdit = false;


    @Override
    protected View initFragment(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_main_shopping_car, container, false);
        return binding.getRoot();
    }

    @Override
    protected void initViews(View rootView) {

        if (adapter.getItemCount() == 0) {
            binding.shoppingPlaceHolder.setVisibility(View.VISIBLE);
        } else {
            binding.shoppingPlaceHolder.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
    }

    /**
     * @param isRefresh 是否是刷新
     */
    private void getDataFromDb(final boolean isRefresh) {
        asyncSession.setListenerMainThread(new AsyncOperationListener() {
            @Override
            public void onAsyncOperationCompleted(AsyncOperation operation) {

                isLoading = false;
                if (isRefresh) {
                    viewStubBinding.mainShoppingCarSwipeRefreshLayout.setRefreshing(false);
                }

                if (operation.isFailed()) {
                    Toast.makeText(mActivity, "获取购物车数据错误", Toast.LENGTH_SHORT).show();
                    Toast.makeText(mActivity, "" + operation.getThrowable().getMessage(), Toast.LENGTH_SHORT).show();
                    return;
                }

                if (operation.getType() == AsyncOperation.OperationType.QueryList) {
                    if (operation.getResult() != null && operation.getResult() instanceof List) {

                        ArrayList<ShoppingCar> shopCar = (ArrayList<ShoppingCar>) operation.getResult();
                        adapter.setShoppingCars(shopCar);

                        if (adapter.getItemCount() == 0) {
                            binding.shoppingPlaceHolder.setVisibility(View.VISIBLE);
                        } else {
                            binding.shoppingPlaceHolder.setVisibility(View.GONE);
                        }

                        if (shopCar.size() > 0) {
                            if (!binding.mainShoppingCarViewStub.isInflated()) {
                                binding.mainShoppingCarViewStub.getViewStub().inflate();
                            }
                        }

                    }

                }

            }
        });
        asyncSession.queryList(QueryBuilder.internalCreate(OrderApplication.getDaoSession().getDao(ShoppingCar.class)).build());
        isLoading = true;
    }

    @Override
    protected void addListener() {

        binding.mainShoppingCarViewStub.setOnInflateListener(new ViewStub.OnInflateListener() {
            @Override
            public void onInflate(ViewStub stub, final View inflated) {
                viewStubBinding = DataBindingUtil.bind(inflated);

                viewStubBinding.mainShoppingCarRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
                viewStubBinding.mainShoppingCarRecyclerView.setAdapter(adapter);


                if (adapter.getSelectedGoodsSize() != 0) {
                    ShoppingCarFragment.this.isSelected = true;
                    viewStubBinding.mainShoppingCarSelectTv.setSelected(true);
                    viewStubBinding.mainShoppingCarSelectTv.setText("( " + adapter.getSelectedGoodsSize() + " )");
                    viewStubBinding.mainShoppingCarPriceTv.setText("¥ " + adapter.getSelectedPrice());
                }

                viewStubBinding.mainShoppingCarSelectTv.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!ShoppingCarFragment.this.isSelected) {
                            ShoppingCarFragment.this.isSelected = true;
//                            Toast.makeText(mActivity, "执行全选", Toast.LENGTH_SHORT).show();
                            adapter.setSelectedGoods(true);
                            viewStubBinding.mainShoppingCarSelectTv.setSelected(true);
                            viewStubBinding.mainShoppingCarSelectTv.setText("( " + adapter.getSelectedGoodsSize() + " )");
                        } else {

                            ShoppingCarFragment.this.isSelected = false;
                            adapter.setSelectedGoods(false);
                            viewStubBinding.mainShoppingCarSelectTv.setSelected(false);
                            viewStubBinding.mainShoppingCarSelectTv.setText(ALL_SELECT);
                        }

                        viewStubBinding.mainShoppingCarPriceTv.setText("¥ " + adapter.getSelectedPrice());


                    }
                });


                viewStubBinding.mainShoppingCarSettlement.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (adapter.getSelectedGoodsSize() != 0) {
                            //    2017/8/22 跳转到确认订单 ---jinXiong

                            if (isEdit){
                                //执行删除操作
                                adapter.deleteSelectedFromShoppingCars(adapter.getSelectedGoods());
                                adapter.clearSelectedShoppingCar();

                                isEdit = false;
                                viewStubBinding.mainShoppingCarSettlement.setText("结算");
                                viewStubBinding.mainShoppingCarSelectTv.setSelected(false);
                                viewStubBinding.mainShoppingCarSelectTv.setText(ALL_SELECT);
                                viewStubBinding.mainShoppingCarPriceTv.setText("¥ " + adapter.getSelectedPrice());

                                return;
                            }

//
                            if (!UserManager.isBingAccount()) {
                                Toast.makeText(mActivity, "请先登录", Toast.LENGTH_SHORT).show();
                                return;
                            }

                            Intent intent = new Intent(ShoppingCarFragment.this.getActivity(), ConfirmOrderActivity.class);
                            intent.putExtra("shoppingCars", adapter.getSelectedGoods());
                            intent.putExtra("goodsPrice", adapter.getSelectedPrice());

                            startActivityForResult(intent, REQUEST_CODE);
                        }
                    }
                });

                viewStubBinding.mainShoppingCarSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                    @Override
                    public void onRefresh() {

                        if (isLoading && isMultiplicationClick()) {
                            return;
                        }
                        getDataFromDb(true);
                    }
                });

            }
        });


        adapter.setCallback(new MainShoppingCarRecyclerViewAdapter.SelectCallBack() {
            @Override
            public void callback(ArrayList<ShoppingCar> objects) {

                if (viewStubBinding == null) {
                    Toast.makeText(mActivity, "error", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (objects == null || objects.size() == 0) {
                    ShoppingCarFragment.this.isSelected = false;
                    viewStubBinding.mainShoppingCarSelectTv.setSelected(false);
                    viewStubBinding.mainShoppingCarSelectTv.setText(ALL_SELECT);
                } else {
                    ShoppingCarFragment.this.isSelected = true;
                    viewStubBinding.mainShoppingCarSelectTv.setSelected(true);
                    viewStubBinding.mainShoppingCarSelectTv.setText("( " + objects.size() + " )");
                }

                viewStubBinding.mainShoppingCarPriceTv.setText("¥ " + adapter.getSelectedPrice());


            }
        });


    }

    @Override
    public void actionBarSetting(FeidiActionBar view) {
        view.setVisibility(View.VISIBLE);
        view.getFallbackView().setVisibility(View.GONE);
        view.getMessageView().setVisibility(View.INVISIBLE);
        view.getSettingView().setVisibility(View.VISIBLE);
        view.setScanCodeView(View.INVISIBLE);
        view.setSettingText("编辑");
        view.setTitleText("购物车");

        view.getSettingView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isEdit) {
                    isEdit = false;
                    viewStubBinding.mainShoppingCarSettlement.setText("结算");
                } else {
                    isEdit = true;
                    viewStubBinding.mainShoppingCarSettlement.setText("删除");
                }
            }
        });
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CODE) {

            switch (resultCode) {


                case CONFIRM_ORDER_RESULT: {

                    boolean success = data.getBooleanExtra("success", false);
                    if (success) {
                        afterOrder();
                    }

                    break;
                }
            }

        }

    }

    /**
     * 成功下订单之后
     */
    private void afterOrder() {

        int size = adapter.getSelectedGoodsSize();

        ArrayList<ShoppingCar> shoppingCars = adapter.getSelectedGoods();

        for (int i = 0; i < size; i++) {
            asyncSession.delete(shoppingCars.get(i), i);
        }

        adapter.clearSelectedFromShoppingCars(shoppingCars);
        adapter.clearSelectedShoppingCar();


        ShoppingCarFragment.this.isSelected = false;
        viewStubBinding.mainShoppingCarSelectTv.setSelected(false);
        viewStubBinding.mainShoppingCarSelectTv.setText(ALL_SELECT);
        viewStubBinding.mainShoppingCarPriceTv.setText("¥ " + adapter.getSelectedPrice());

    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        adapter = new MainShoppingCarRecyclerViewAdapter(this);
        asyncSession = OrderApplication.getDaoSession().startAsyncSession();
    }

    @Override
    public void onResume() {
        super.onResume();
        getDataFromDb(false);
    }
}
